package com.jitu.ffmpegpushrtsp;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Configuration
public class FFmpeg {

    @Value("${rtsp.file_addr}")
    private String fileAddr;

    @Value("${rtsp.stream_loop}")
    private Integer stream_loop;

    @Bean
    public void pushRTSP() {
        if (fileAddr == null) {
            return;
        }

        if (stream_loop == null) {

            stream_loop = 1;
        }

        push(files());
    }

    private List<String> files() {

        List<String> files = new ArrayList<>();

        if (fileAddr.endsWith("/")) {

            fileAddr = fileAddr.substring(0, fileAddr.length() -1);
        }

        File file = new File(fileAddr);

        if (!(file.isAbsolute() && file.exists() && file.isDirectory())) {

            return null;
        }

        for (File f : Objects.requireNonNull(file.listFiles())) {

            files.add(f.getName());
        }

        return files;
    }

    private void push(List<String> files){

        if (files == null) {
            return;
        }

        for (String f : files) {

            String ffmpeg = "nohup ffmpeg -re -stream_loop " + stream_loop + " -i " + fileAddr + "/" + f + " -c copy -f rtsp rtsp://localhost/live/" + f.split("\\.")[0] + " > /dev/null 2>&1 &";

            System.out.println(ffmpeg);

            try {
                Runtime.getRuntime().exec(new String[]{"/bin/bash", "-c", ffmpeg});
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
